package com.example.lenovo_.healthyangel;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.example.lenovo_.healthyangel.User.User;
import com.example.lenovo_.healthyangel.User.sendInfor;
import com.example.lenovo_.myactivity.LoginActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by lenovo- on 2016/10/10.
 */
public class RegisterActivity extends AppCompatActivity implements View.OnClickListener {
    private Button bt1;
    private EditText et1, et2, et3, et4;
    private static ProgressDialog dialog;
    private String TAG = "info";
    private static String PHPSESSID = null;
    User user = new User();
    hander h1 = new hander();
    sendInfor send = new sendInfor();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.register);
        bt1 = (Button) findViewById(R.id.button4);
        et1 = (EditText) findViewById(R.id.editText6);
        et2 = (EditText) findViewById(R.id.editText3);
        et3 = (EditText) findViewById(R.id.editText4);
        et4 = (EditText) findViewById(R.id.editText5);
        bt1.setOnClickListener(this);
        send.setRequestPath("http://121.42.190.59/healthyangel/controller/register.php");
    }

    @Override
    public void onClick(View v) {
        if (checkRegister()) {
            if (dialog == null) {
                dialog = new ProgressDialog(this);
            }
            dialog.setTitle("再等人家一会嘛~");//弹出一个Dialog
            dialog.setMessage("正在登录中...");
            dialog.setCancelable(false);
            dialog.show();
            StartRequest();//请求服务器端
        }

    }

    public class hander extends Handler {
        @Override
        public void handleMessage(Message msg) {
            int flag = msg.what;
            switch (flag) {
                case 1:
                    show(1);
                    break;
                case 2:
                    show(2);
                    break;
                case 3:
                    show(3);
                    break;
                case 4:
                    show(4);
                    break;
                default:
                    break;
            }
        }
    }

    public void show(int i) {
        if (dialog != null) {
            dialog.dismiss();
        }
        switch (i) {
            case 1:
                Toast.makeText(this, "注册成功", Toast.LENGTH_SHORT);
                Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
                startActivity(intent);
                break;
            case 2:
                Toast.makeText(this, "用户已存在", Toast.LENGTH_SHORT);
                break;
            case 3:
                Toast.makeText(this, "服务器故障", Toast.LENGTH_SHORT);
                break;
            case 4:
                Toast.makeText(this, "连接超时，请检查网络", Toast.LENGTH_SHORT);
                break;
            default:
                break;
        }
    }

    private boolean checkRegister() {
        //若4个editText都不空时
        if (!et1.getText().toString().equals("") && !et2.getText().toString().equals("") && !et3.getText().toString().equals("") && !et4.getText().toString().equals("")) {
            if(et4.getText().toString().equals(et3.getText().toString())){
                //将信息传递到服务器
                user.setName(et1.getText().toString());
                user.setPhonenumber(et2.getText().toString());
                user.setPassword(et3.getText().toString());
                return true;
            }else {
                Toast.makeText(this,"密码不一致，请重新输入",Toast.LENGTH_SHORT);
                return false;
            }
        }else {
            Toast.makeText(this,"请填写完整",Toast.LENGTH_SHORT);
            return false;
        }
    }
    private void StartRequest(){
        //新建线程
        new Thread(){
            public void run(){
                try {
                    sendRequest();
                } catch (Exception e){
                    e.printStackTrace();
                }
            }
        }.start();
    }
    private void sendRequest() throws IOException, JSONException {
        HttpURLConnection urlcon=null;
        try{
            //通过HttpURLConnection完成发送请求
            //请求WEB资源
            String ServerUrl=send.getRequestPath();
            URL url=new URL(ServerUrl);
            urlcon = (HttpURLConnection) url.openConnection();
            //使用get的方式
            urlcon.setRequestMethod("GET");
            //连接主机超时，通过setConnectTimeOut方法
            urlcon.setConnectTimeout(30000);
            //从主机读取数据超时，通过setReadTimeout方法
            urlcon.setReadTimeout(30000);
            //准备传输的数据
            send.getSendRequest(new JSONObject());
            send.getSendRequest(new JSONObject()).put("name",user.getName());
            send.getSendRequest(new JSONObject()).put("phonenumber",user.getPhonenumber());
            send.getSendRequest(new JSONObject()).put("password",user.getPassword());
            if(urlcon.getResponseCode()==200){
                //获取输入流
                InputStream is=urlcon.getInputStream();
                //输入流转化为StringBuilder
                BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(is));
                StringBuilder builder=new StringBuilder();
                String data;
                try {
                    while ((data=bufferedReader.readLine())!=null){
                        builder.append(data);
                    }
                    //输出结果
                    System.out.println(builder.toString());
                    //得到Json对象
                    send.setReceResponce(new JSONObject(builder.toString()));

                    int flag=send.getReceResponce().getInt("flag");
                    String sessionid=send.getReceResponce().getString("session_id");
                    PHPSESSID=sessionid;
                    if (flag==1){
                        h1.sendEmptyMessage(1);//成功
                    }else if (flag==2){
                        h1.sendEmptyMessage(2);//用户名已存在
                    }else {
                        h1.sendEmptyMessage(3);//服务器故障
                    }
                }catch (IOException e){
                    e.printStackTrace();
                    h1.sendEmptyMessage(4);//无连接网络
                }
                //封装数据并发送

            }
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            if (urlcon != null) {
                urlcon.disconnect();//关闭连接
            }
        }
    }
}

